var contextPath = $("#contextPath").val();
var referrer = $("#referrer");
var grade = $("#grade");
var explain = $("#explain");
var code = $("#code").val();
var login = $("#login");
var load;
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
var urlCode = getUrlParam('code');
var phone_reg = /^1[3|4|5|7|8]\d{9}$/;
var pa=/^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,22}$/;

$(function(){
	
	var basePath;
	;$(function(){
		sendCode();
		basePath = $(".basePath").attr("url");
		if(basePath == undefined){
			basePath = $("#contextPath").val();
		}
	});

	dataInit(code);
	
	
	//提交按钮的点击（jQuery 参数的验证）
	$("#updatevip").click(function(){
		
		//var parentPhone = $("#parentPhone").val();   //推荐人手机号
		var userName = $("#userName").val();         //当前用户的手机号
		var level = parseInt($(".vip_select_active").attr("level"));     //vip等级
		var totalPrice = $("#totalPrice").val();     //充值金额
//		if($.trim(parentPhone).length > 0){
//		if(!phone_reg.test(parentPhone)){
//			layer.open({
//			    content:'你所输入手机号码不合法请仔细检查!',
//			    time: 2
//			});
//		 return false;
//		}
//		}
		
//		if(parentPhone == userName){
//			layer.open({
//			    content:'推荐人的手机号不能为自己',
//			    time: 2
//			});
//		 return false;
//		}
		if(level <= 0){
			layer.open({
			    content:'VIP等级错误',
			    time: 2
			});
		 return false;
		}
		if(parseFloat(totalPrice) <= 0){
			layer.open({
			    content:'您已经是VIP&nbsp;'+level,
			    time: 2
			});
		 return false;
		}
		
		var payMode = $("#payMode").val();
		
		if(payMode == '00'){
			layer.open({
			    title: '提示',
			    content: '请选择支付方式',
			    btn: ['我知道了']
			});	
			return;
		}
		
		var paramsone = {totalPrice:totalPrice,level:level};
		load = layer.open({type: 2,shadeClose:false});
		
		if(payMode == 'YE'){
			balancePayVip(paramsone)
		}
	});

	//支付
function balancePayVip(paramsone){
	$.ajax({
		url:contextPath+"/myvip/balance_pay_vip",
		type:"post",
		async:true,
		data:paramsone,
		dataType:"json",
		success : function(data, textStatus) {
			layer.close(load);
			var state = data.result.state;
			if(state == 1){
				layer.open({
				    title: '提示',
				    content: '充值VIP成功！',
				    btn: ['我知道了'],
				    yes: function(index){
				    	location.href=contextPath+"/user/myvip";
				    }
				});	
			}else{
				var message = data.result.message;
				var url = data.result.url;
				layer.open({
				    title: '提示',
				    content: message,
				    btn: ['我知道了'],
				    yes: function(index){
				    	layer.close(index);
				        if(message == "用户未登录"){
				        	init();
						}
				    }
				});	
			}
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			layer.close(load);
		}
	});	
}
	
	$("#login").click(function(){
		//用户登录
		var userName = $("#userName1").val();
		var password = $("#password1").val();
		var forward = $("#forward").val();
		
				 if($.trim(userName).length<=0){
					 layer.open({
						    content:'请输入手机号码',
						    time: 2
						});
					 return false;
				 }
				 if(!phone_reg.test(userName)){ 
					 layer.open({
						    content:'手机号码有误，请重填',
						    time: 2
						});
			        return false; 
			     } 
				 if($.trim(password).length<=0){
					 layer.open({
						    content:'请输入您的密码!',
						    time: 2
						});
					 return false; 
				 }
				 var param = {userName:userName,pwd:password};
				 $.ajax({
					 url:contextPath+"/login",
					 async:true,
					 data:param,
					 type:'post',
					 dataType:"json",
					 success:function(data, textStatus){
						 if(data.result.state == 1){
							 if(data.result.message == 'userIsNull'){
								 layer.open({
									    content:'手机号或密码不正确',
									    time: 2
									});
							 }else{
								 layer.open({
									    content:'登录成功!',
									    time: 2
									});
								 closeFn();
							 }
						 }
					 },
					 error:function(XMLHttpRequest, textStatus, errorThrown){
						 layer.open({
							    content:textStatus,
							    time: 2
							});
					 }
				 });
	});
	
	/**发送验证码**/
	var sendCode = function(){
		$("#getcode").on("click",function(){
			$('#getcode').unbind("click");
			var userName = $("#userName2").val();
			var type = $("#types").val();
			if($.trim(userName).length<=0){
				layer.open({
				    content:'请输入注册时使用的手机号码!',
				    time: 2
				});
				sendCode();
				 return false; 
			}
			if(!phone_reg.test(userName)){
				 layer.open({
					    content:'你所输入手机号码不合法请仔细检查!',
					    time: 2
					});
				 sendCode();
				 return false; 
			}
			$.ajax({
				url:basePath+'/send',
				data:{userName:userName,type:type},
				type:'post',
				success:function(data){
					if(data.sendNum < 2){
						 layer.open({
							    content:'您的验证码是:'+data.code,
							    btn: ['确认']
						   });
							if(data.result.state == 1 && data.result.code =='100001'){
								var codeHidden=$("#codeHidden").val();
								if(codeHidden != undefined){
									$("#codeHidden").val(data.code);
								}
								countdown(data.result.message,data.sendNum);
							}
					}else{
						$(".ui_btn_success").css({backgroundColor:'#ffffff',color:'#00b18f'});
						$(".ui_btn_success").html('发送次数达到当天限制');
						$(".ui_btn_success").removeClass("sendCode");
					}
				},
				error:function(e){
					 layer.open({
						    content:'获取验证码错误请稍刷新后再试',
						    time: 2
					   });
				}
			});
		});
	}
	var seTips = function() {
		$(".tips-box").css({'color':'red'});
		setTimeout(function(){
			$(".tips-box").html('');
		}, 2000)
	}
	var miao;
	var  countdown= function (msg,sendNum){
		miao=msg;
		if(sendNum>= 2){
		}else{
			$(".ui_btn_success").css({backgroundColor:'#ffffff',color:'#00b18f'});
			$(".ui_btn_success").html(msg+'秒后重发');
			var time=setInterval(function(){
				if(sendNum > msg){
					window.clearInterval(time);
				}
				msg--;
				if(msg == 0){
					window.clearInterval(time);
					$(".ui_btn_success").css({backgroundColor:'#00b18f',color:'#fff'});
					$(".ui_btn_success").html('获取验证码');
					sendCode();
					msg=miao;
					sendNum++;
					return false;
				}else{
					$(".ui_btn_success").html(msg+'秒后重发');
				}
			}, 1000)
		}
	}

	/**注册**/
	var isSelected = true;
	form.Checkbox('.reg_notice',{
		onchange:function(Form){
			isSelected = Form.iSelect;
		}
	});
	$("#register").click(function(){
		
		var userName = $("#userName2").val();
		var pasword = $("#pasword2").val();
		var code = $("#codes").val();
		if($.trim(userName).length<=0){
			layer.open({
			    content:'请输入注册时使用的手机号码!',
			    time: 2
			});
			 return false; 
		}
		if(!phone_reg.test(userName)){
			layer.open({
			    content:'你所输入手机号码不合法请仔细检查!',
			    time: 2
			});
			 return false; 
		}
		
		if($.trim(pasword).length <= 0) {
			layer.open({
			    content:'你所输入密码',
			    time: 2
			});
			return false;
		}
		if(!pa.test(pasword)){
			layer.open({
			    content:'密码有6~20位英文字母/数字或符号组成',
			    time: 2
			});
			return false;
		}
		if($.trim(code).length <=0 ){
			layer.open({
			    content:'你所输入验证码',
			    time: 2
			});
			return false;
		}
		//判断是否选定  同意
		if(!isSelected){
			layer.open({
			    content:'请您仔细阅读《注册协议》，在您同意之后点击注册!',
			    time: 2
			});
			 return false; 
		}
		var pamam = {mobile:userName,pasword:pasword,code:code,type:'register'}
		$.ajax({
			url:contextPath+'/register',
			data:pamam,
			type:'post',
			success:function(data){
				if(data.result.code == 'exist'){
					layer.open({
					    content:'此手机号码已注册请更换其他号码!',
					    time: 2
					});
					return false;
				}
				if(data.result.code == 'error'){
					layer.open({
					    content:'验证码输入错误!',
					    time: 2
					});
					return false;
				}
				if(data.result.code == 'expire'){
					layer.open({
					    content:'验证码已过期!',
					    time: 2
					});
					return false;
				}
			
				if(data.result.code == 'ok'){
					layer.open({
					    content:'恭喜您注册成功',
					    time: 2
					});
					 closeFn();
				}
			},
			error:function(data){
				
			}
		});
	});

	/**验证手机收到验证码是否有效**/
	var UpdateNewPwd = function(){
		var userPhone = $("#userName").val();
		var code = $("#code").val();
		var password = $("#types").val();
		if(phone_reg.test(userName)){
			layer.open({
			    content:'你所输入手机号码不合法请仔细检查!',
			    time: 10000
			});
			return false; 
		}
		if(code.length <=0){
			layer.open({
			    content:'请输入手机收到的验证码!',
			    time: 10000
			});
			return false; 
		}
		var params = {mobile:userPhone,code:code,type:password};
		$.ajax({
			url:contextPath+"/toNewsPwd",
			data:params,
			type:'post',
			dataType:'json',
			success:function(data){
					if(data.result.message != undefined && data.result.message == '0001'){
						layer.open({
						    content:'验证码输入错误!',
						    time: 10000
						});
						return false;
					}
					if (data.next != '') {
						window.location =basePath+ data.next;
					}
			},
			error:function(data){
				layer.open({
				    content:data,
				    time: 2
				});
			}
		});
	}

	//微信   银联  余额支付的切换
	form.Radio('.data_radio', {
	    onchange: function(radios, _this) {
	    	var val = _this.querySelector('a').getAttribute('payMode');
	    	$("#payMode").val(val);
	    	
	    }
	  });
});
//数据的显示
function dataInit(code){
	$.ajax({
		url:contextPath+"/myvip/upgrade",
		type:"post",
		async:true,
		data:{code:code},
		dataType:"json",
		success : function(data, textStatus) {
//			if (data.parentuser != null) {
//				referrer.append('<div class="ui_cell"><div class="ui_cell_bd"><input  class="ui_input" id="parentPhone" value="'+data.parentuser.phone+'" placeholder="'+data.parentuser.phone+'" readonly type="text"></div></div>');
//			}else if(data.parentuser == null){
//				referrer.append('<div class="ui_cell"><div class="ui_cell_bd"><input class="ui_input" id="parentPhone" type = "text" placeholder="推荐人(手机号)" type="text"></div></div>');
//			}
			//参数的初始化
			referrer.append('<input type="hidden" id="userName" value="'+data.user+'">');
			referrer.append('<input type="hidden" id="totalPrice" name="totalPrice" value="0">');
			referrer.append('<input type="hidden" id="level" name="level" value="0">');
			referrer.append('<input type="hidden" id="payMode" name="payMode" value="YE">');
			var vip = data.vipprice;
			$.each(data.vipAllLevel,function(i,v){
				console.log(data.userlevel +"=="+ v.level);
				if(data.userlevel > v.level){
					grade.append('<span class="vip_type_item" style="background:#E0EEEE" price="'+v.price+'" level="'+v.level+'">'+v.name+'<input type="hidden" value="'+v.explain+'"></span>');
				}else if(data.userlevel == v.level){
					grade.append('<span class="vip_click vip_type_item vip_select_active"  price="'+v.price+'" userprice="'+vip+'" level="'+v.level+'">'+v.name+'<input type="hidden" value="'+v.explain+'"></span>');
					explain.find("textarea").text("您是的用户等级为  ："+v.name+"  , 您已经充值 (元)  "+vip);
				}else{
				grade.append('<span class="vip_click vip_type_item" userprice="'+vip+'" price="'+v.price+'" level="'+v.level+'">'+v.name+'<input type="hidden" value="'+v.explain+'"></span>');
				}
			});
			var active = $(".vip_select").find(".vip_select_active").size();
			if(active == 0){
				$($(".vip_select").find("span")[0]).addClass("vip_select_active");
				var price = $($(".vip_select").find("span")[0]).attr("price");
				$("textarea").text($($(".vip_select").find("span")[0]).find("input").val() +""+ price);
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			alert(textStatus+"123");
		}
	});		
}

//按钮的选择
$(document).on("click",".vip_click",function(){
	$(".vip_select_active").removeClass("vip_select_active");
	$(this).addClass("vip_select_active");
	
	var vipprice = $(this).attr("price"); // 用户要提升的vip等级的金额
	var level = $(this).attr("level");   //用户要提升的vip等级
	var userprice = $(this).attr("userprice");// 当前用户的vip金额
	
	var price = vipprice-userprice;
	if (userprice != 0) {
		    //参数的设置
			$("#totalPrice").val(price);
			$("#level").val(level);
	
		explain.find("textarea").text($(this).find("input").val()+vipprice+"  : 还需  "+price+"(元)");
	}else {
		explain.find("textarea").text($(this).find("input").val()+vipprice);
		  //参数的设置
		$("#totalPrice").val(vipprice);
		$("#level").val(level);
	}
	
});
